package fr.curriculumvitae.anthony.stephan.activities;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import fr.curriculumvitae.anthony.stephan.R;
import fr.curriculumvitae.anthony.stephan.SwipeyTabsActivity;
import fr.curriculumvitae.anthony.stephan.backend.BackEnd;
import fr.curriculumvitae.anthony.stephan.backend.IAuthentificationCallback;

public class PwdPickerActivity extends Activity {
	
	public static final String EXTRA_DISMISS_DIALOG = "dismissDialog";
	private static final String EMPTY = "";
	
	private static Context context;
	
	private EditText etPwd;
	private Button bActionValid;
	
	private boolean dismissDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// dismiss action bar
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
        // set content view
		setContentView(R.layout.activity_pwd_picker);
		context = this;
		
		// get extras
		Bundle extras = getIntent().getExtras();
		if(extras != null) {
			dismissDialog = (Boolean) extras.get(EXTRA_DISMISS_DIALOG);
		} else {
			dismissDialog = true;
		}
		
		// adapt width & height (with max limits if needed)
        final LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout_pwd_picker);
        ViewTreeObserver vto = layout.getViewTreeObserver(); 
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
            @SuppressWarnings("deprecation")
			@Override 
            public void onGlobalLayout() { 
            	layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                DisplayMetrics metrics = getResources().getDisplayMetrics();
                int activityFinalWidth = (int) (metrics.widthPixels * 0.90);
                int activityFinalHeight = (int) (metrics.heightPixels * 0.75);
                getWindow().setLayout(activityFinalWidth, activityFinalHeight);
            } 
        });
        
        fetchViews();
        customizeViews();
        setListeners();
	}
	
	
	private void fetchViews() {
		etPwd = (EditText) findViewById(R.id.editText_pwd_picker);
		bActionValid = (Button) findViewById(R.id.button_pwd_picker);
	}
	
	private void customizeViews() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}
	
	private void setListeners() {
		bActionValid.setOnClickListener(onSendClickListener);
		etPwd.setOnTouchListener(onEditTextTouchListener);
	}
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		// dismiss dialog if needed :
		if(SwipeyTabsActivity.mDialog != null) {
			SwipeyTabsActivity.mDialog.dismiss();
		}
	}
	
	
	  ///////////////
	 // LISTENERS //
	///////////////
	
	private OnClickListener onSendClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String pwd = etPwd.getEditableText().toString();
			if(pwd == null || pwd.equals(EMPTY)) {
				etPwd.setHintTextColor(Color.RED);
				etPwd.setHint(R.string.contact_form_error_enterprise);
				return;
			}
			// close keyboard :
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(etPwd.getWindowToken(), 0);
			// open progress dialog :
			SwipeyTabsActivity.mDialog = ProgressDialog.show(context, 
					getResources().getString(R.string.pwd_picker_dialog_title), 
					getResources().getString(R.string.pwd_picker_dialog_message));
			BackEnd.authentification(pwd, authentificationCallback);
		}
	};
	
	
	private OnTouchListener onEditTextTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if(v instanceof EditText) {
				EditText etv = (EditText) v;
				etv.setHintTextColor(Color.GRAY);
			}
			return false;
		}
	};
	
	
	  ///////////////
	 // CALLBACKS //
	///////////////
	
	private IAuthentificationCallback authentificationCallback = new IAuthentificationCallback() {
		@Override
		public void authentificationEnded(boolean success, String message) {
			if(success) {
				setResult(RESULT_OK);
			} else {
				setResult(Activity.RESULT_FIRST_USER);
			}
			if(dismissDialog && SwipeyTabsActivity.mDialog!=null) {
				SwipeyTabsActivity.mDialog.dismiss();
			}
			finish();
		}
	};
	
}
